/* fsl_uart.c */
#include "fsl_uart.h"

void UART_ConfigTransfer(UART_Type *devPtr, const UART_Config_T *configPtr)
{
    uint16_t sbr_val;

    if (!configPtr) /* Reset the module. */
    {
        devPtr->C1 = 0U;
        devPtr->C2 = 0U;
        devPtr->C3 = 0U;
        devPtr->S2 = UART_S2_LBKDIF_MASK | UART_S2_LBKDIF_MASK;
        devPtr->BDH = 0U;
        devPtr->BDL = 0x4;
        return;
    }
    /* Disable the Rx and Tx. */
    devPtr->C2 &= ~(UART_C2_TE_MASK | UART_C2_RE_MASK);
    
    /* configure uart1 for 8-bit mode , no parity */
    devPtr->C1 = 0U;

    /* calculate the sbr value. */
    sbr_val = (configPtr->BusClkHz >> 4)/configPtr->Baudrate;
    devPtr->BDH = (uint8_t)(((0x1F00 & sbr_val) >> 8)&UART_BDH_SBR_MASK);
    devPtr->BDL = (uint8_t)(sbr_val & UART_BDL_SBR_MASK);
    
    devPtr->C3 = 0U;
    devPtr->S2 = 0U;
    
    /* enable the tx and rx  */
    devPtr->C2 |= (UART_C2_TE_MASK | UART_C2_RE_MASK);
}

void UART_SetIntEnabledOnTxBufferEmpty(UART_Type *devPtr, bool enInt)
{
    if (enInt)
    {
        devPtr->C2 |= UART_C2_TCIE_MASK;
    }
    else
    {
        devPtr->C2 &= ~UART_C2_TCIE_MASK;
    }
}
void UART_SetIntEnabledOnRxBufferFull(UART_Type *devPtr, bool enInt)
{
    if (enInt)
    {
        devPtr->C2 |= UART_C2_RIE_MASK;
    }
    else
    {
        devPtr->C2 &= ~UART_C2_RIE_MASK;
    }
}

void UART_PutTxData(UART_Type *devPtr, uint8_t txData)
{
    devPtr->D = txData;
}
bool UART_IsTxBufferEmpty(UART_Type *devPtr)
{
    return ( 0U != (devPtr->S1 & UART_S1_TDRE_MASK) );
}
void UART_PutTxDataBlocking(UART_Type *devPtr, uint8_t txData)
{
    while (!UART_IsTxBufferEmpty(devPtr) ) {}
    UART_PutTxData(devPtr, txData);
}

uint8_t UART_GetRxData(UART_Type *devPtr)
{
    return devPtr->D;
}
bool UART_IsRxBufferFull(UART_Type *devPtr)
{
    return (0U != (devPtr->S1 & UART_S1_RDRF_MASK) );
}

void UART_SetTxDMAMode(UART_Type *devPtr, bool val)
{
    if(val)
    {
        devPtr->C2 |= UART_C2_TIE_MASK;
        devPtr->C5 |= UART_C5_TDMAS_MASK;
    }
    else
    {
        devPtr->C2 &= ~UART_C2_TIE_MASK;
        devPtr->C5 &= ~UART_C5_TDMAS_MASK;
    }

}

uint8_t UART_GetRxDataBlocking(UART_Type *devPtr)
{
    while (!UART_IsRxBufferFull(devPtr)) {}
    return UART_GetRxData(devPtr);
}

/* EOF. */
